/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.manage.core.manage.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Sets;
import info.peigen.hotpot.common.core.enums.Messageable;
import info.peigen.hotpot.common.core.result.manage.WebResult;
import info.peigen.hotpot.manage.core.config.HotpotManageProperties;
import info.peigen.hotpot.manage.core.manage.form.EnumSelectionForm;
import org.noear.solon.annotation.*;
import org.noear.solon.core.bean.LifecycleBean;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>(CommonController)</b>
 *
 * @author Lihai
 * @version 1.0.0
 * @since 2023/8/16
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Controller
@Mapping("/common/")
@Configuration
public class CommonController implements LifecycleBean {
    static Map<String, ? extends Class<?>> enumMap;

    @Inject
    HotpotManageProperties hotpotManageProperties;

    @Mapping("enumSelection")
    public WebResult enumSelection(@Body EnumSelectionForm form) {
        if (CollUtil.isNotEmpty(form.getNames())) {
            Map<String, List<Messageable>> enumMapResult = new HashMap<>();
            form.getNames().forEach(each -> enumMapResult.put(each, getByName(each)));
            return WebResult.setSuccessResult().setInfo(enumMapResult);
        }
        return WebResult.setSuccessResult().setInfo(null);
    }

    @Override
    public void start() {
        Set<Class<?>> hotpotEnumsClasses = ClassScanner.scanPackageBySuper("info.peigen.hotpot", Messageable.class);
        Set<Class<?>> classes            = Sets.newHashSet();
        classes.addAll(hotpotEnumsClasses);
        String enumPackage = hotpotManageProperties.getEnumPackage();

        // 为Project工程里面的枚举增加扫描
        if (StrUtil.isNotEmpty(enumPackage)) {
            Set<Class<?>> projectEnumsClasses = ClassScanner.scanPackageBySuper(enumPackage, Messageable.class);
            classes.addAll(projectEnumsClasses);

        }
        enumMap = classes.stream().collect(Collectors.toMap(each -> each.getSimpleName()
                .toUpperCase(), each -> each, (enum1, enum2) -> enum1));
    }

    private List<Messageable> getByName(String name) {
        List<Messageable> result    = new ArrayList<>();
        Class<?>          enumClass = enumMap.get(name.toUpperCase());
        if (ObjectUtil.isNotNull(enumClass)) {
            result.addAll(ReflectUtil.invokeStatic(ReflectUtil.getMethodByName(enumClass, "getAllEnum")));
            result = result.stream().filter(each -> !"--".equals(each.code())).collect(Collectors.toList());
        }
        return result;
    }
}